#!/bin/sh

# Define the rtos_boot command
RTOS_BOOT="/sys/kernel/rtos_boot" # Path to the rtos_boot sysfs entry
RTOS_CORE="3"                     # RTOS core number
RTOS_BOOT_MODE="./rtos_boot.ko"   # Path to the rtos_boot.ko file
RTOS_IMAGE="./rtthread.bin"       # Path to the rtthread.bin file

# Function to display usage
usage() {
  echo "Usage: $0 <command> [options]"
  echo "Commands:"
  echo "  help                 Display this help message."
  echo "  load -f <file_path>  Load the specified file."
  echo "  boot -c <core>       Boot the specified core."
  echo "  start -c <cores>     Start with the specified number of cores."
  echo "  mem -p <address>     Display memory at the specified address."
  echo "  mem -s <size>        Set memory size."
  exit 1
}

# Check if at least one argument is provided
if [ $# -lt 1 ]; then
  usage
fi

# Convert relative paths to absolute paths
resolve_path() {
  local path="$1"
  if [ ! -e "$path" ]; then
    echo "Error: File does not exist - $path"
    exit 1
  fi
  echo "$(cd "$(dirname "$path")" && pwd)/$(basename "$path")"
}

# Parse the command and its options
case $1 in
  help)
    usage
    ;;

  load)
    if [ "$2" == "-f" ] && [ -n "$3" ]; then
      ABS_PATH=$(resolve_path "$3")
      echo "load -f $ABS_PATH" > $RTOS_BOOT
      echo "Command written: load -f $ABS_PATH"
    else
      echo "Error: Missing or invalid arguments for 'load' command"
      usage
    fi
    ;;

  boot)
    if [ "$2" == "-c" ] && [ -n "$3" ]; then
      echo "boot -c $3" > $RTOS_BOOT
      echo "Command written: load -c $3"
    else
      # echo "Error: Missing or invalid arguments for 'boot' command"
      # usage
      echo "Used default image: $RTOS_IMAGE, core: $RTOS_CORE"
      insmod "$RTOS_BOOT_MODE"
      ABS_PATH=$(resolve_path "./$RTOS_IMAGE")
      echo "load -f $ABS_PATH" > $RTOS_BOOT
      echo "boot -c $RTOS_CORE" > $RTOS_BOOT
    fi
    ;;

  start)
    if [ "$2" == "-c" ] && [ -n "$3" ]; then
      echo "start -c $3" > $RTOS_BOOT
      echo "Command written: start -c $3"
    else
      echo "Error: Missing or invalid arguments for 'start' command"
      usage
    fi
    ;;

  mem)
    if [ "$2" == "-p" ] && [ -n "$3" ]; then
      echo "mem -p $3" > $RTOS_BOOT
      echo "Command written: mem -p $3"
    elif [ "$2" == "-s" ] && [ -n "$3" ]; then
      echo "mem -s $3" > $RTOS_BOOT
      echo "Command written: mem -s $3"
    else
      echo "Error: Missing or invalid arguments for 'mem' command"
      usage
    fi
    ;;  

  *)
    echo "Error: Unknown command '$1'"
    usage
    ;;
esac
